package com.example.armmvvm.ui.media.util;

import android.media.MediaPlayer;

public class AudioPlayHelper {

    private static final String TAG = "AudioPlayHelper:--";

    private AudioBean curPlaying;

    private MediaPlayer player;

    public AudioPlayHelper() {
    }

    private void startPlaying(AudioBean audioBean) {
        stopPlaying(curPlaying);
        curPlaying = audioBean;
        startMedia(audioBean);
    }

    private void startMedia(AudioBean audioBean) {
        try {
            player = new MediaPlayer();
            if (audioBean.getLocalPath() != null) {
                player.setDataSource(audioBean.getLocalPath());
            } else {
                player.setDataSource(audioBean.getNetPath());
            }
            player.prepare();
            player.setOnPreparedListener(mp -> mp.start());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopPlaying() {
        if (curPlaying != null) {
            stopPlaying(curPlaying);
        }
    }

    public void stopPlaying(AudioBean audioBean) {
        if (player != null) {
            try {
                if (audioBean != null) {
                    audioBean.setPlaying(false);
                }
                player.stop();
                player.reset();
                player = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isPlaying(AudioBean check) {
        return curPlaying == check;
    }

    public AudioBean getCurPlaying() {
        return curPlaying;
    }

    public void play(AudioBean audioBean) {
        audioBean.setPlaying(true);
        startPlaying(audioBean);
    }

}
